package android.medicalcloud.com.yiapp.yilian.ui.view.adapter;

import android.content.Context;
import android.content.Intent;
import android.medicalcloud.com.yiapp.R;
import android.medicalcloud.com.yiapp.base.adapter.BasePlatAdapter;
import android.medicalcloud.com.yiapp.base.utils.Logger;
import android.medicalcloud.com.yiapp.base.utils.MD5Util;
import android.medicalcloud.com.yiapp.yilian.application.YilianAppcation;
import android.medicalcloud.com.yiapp.yilian.model.FileModel;
import android.medicalcloud.com.yiapp.yilian.ui.view.RoundProgressBar;
import android.medicalcloud.com.yiapp.yilian.utils.android.FileUtils;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by wanggenlin on 17-5-31.
 */
public class FileAdapter extends BasePlatAdapter<FileModel>{

    String dirPath= FileUtils.createSDDir("yilian").getPath();

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView==null){
            convertView = mLayoutInflater.inflate(R.layout.view_file_item,null);
        }
        final FileModel model = getItem(position);
        TextView tv = (TextView)convertView.findViewById(R.id.nameTv);
        tv.setText(model.getName());
        String prefix=model.getUrl().substring(model.getUrl().lastIndexOf(".")+1);
        String path=dirPath+File.separator+model.getName();
        ImageView stauesIv   = (ImageView)convertView.findViewById(R.id.stauesIv);
        if (new File(path).exists()){
            model.setDownLoad(true);
            String name = model.getName();
            if (name.toLowerCase().contains("ppt")||name.toLowerCase().contains("pptx")){
                stauesIv.setImageResource(R.drawable.file_ppt);
            }else if (name.toLowerCase().contains("html")){
                stauesIv.setImageResource(R.drawable.file_html);
            }else if (name.toLowerCase().contains("mp4")||name.toLowerCase().contains("avi")){
                stauesIv.setImageResource(R.drawable.file_mpf);
            }else if(name.toLowerCase().contains("jpg")||name.toLowerCase().contains("jpge")||name.toLowerCase().contains("png")){
                stauesIv.setImageResource(R.drawable.file_jpg);
            }else if(name.toLowerCase().contains("txt")){
                stauesIv.setImageResource(R.drawable.file_txt);
            }else if (name.toLowerCase().contains("doc")||name.toLowerCase().contains("docx")){
                stauesIv.setImageResource(R.drawable.file_doc);
            }else{
                stauesIv.setImageResource(R.drawable.file_ss);
            }
        }else{
            model.setDownLoad(false);
            stauesIv.setImageResource(R.drawable.file_defalut);
        }
        final RoundProgressBar progress   = (RoundProgressBar)convertView.findViewById(R.id.progress);
        final View fileItemView   = convertView.findViewById(R.id.fileItemView);
        progress.setMax(100);
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!model.isDownLoad()){
                    progress.setVisibility(View.VISIBLE);
                    fileItemView.setVisibility(View.GONE);
                    new DowLoadThread(model.getUrl(),model,progress,fileItemView).start();
                    return;
                }
                String path=dirPath+File.separator+model.getName();
                Logger.e("woca = = ="+path);
                File file=new File(path);
                try {
                    String prefix=model.getUrl().substring(model.getUrl().lastIndexOf(".")+1);

                    Intent it =new Intent(Intent.ACTION_VIEW);
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Uri mUri = Uri.parse("file://"+file.getPath());
//                    it.setData(Uri.fromFile(file));
                    if (model.getName().endsWith("txt")){
                        it.setDataAndType(Uri.fromFile(file), "text/plain");
                        YilianAppcation.instance.startActivity(it);
                    }else if (model.getName().endsWith("jpg")||model.getName().endsWith("png")){
                        it.setDataAndType(Uri.fromFile(file), "image/*");
                        YilianAppcation.instance.startActivity(it);
                    }else{
                        Toast.makeText(YilianAppcation.instance,"该文件已经下载的目录为:"+file.getAbsolutePath(),Toast.LENGTH_LONG).show();
                    }

                }catch (Exception E){
                    Toast.makeText(YilianAppcation.instance,"该文件已经下载的目录为:"+file.getAbsolutePath(),Toast.LENGTH_LONG).show();
                }

            }
        });
        return convertView;
    }

    public FileAdapter(Context context) {

        super(context);
    }



    private class DowLoadThread extends Thread {
        String urlStr ="" ;
        FileModel model =null;
        RoundProgressBar view = null;
        int progress;
        ProgressHandler handler ;
        int lastRate = 0;
        View fileItemView;

        public DowLoadThread(String urlStr, FileModel model, RoundProgressBar view,View fileItemView) {
            this.urlStr = urlStr;
            this.model = model;
            this.view = view;
            handler = new ProgressHandler(view,model,fileItemView);
            this.fileItemView = fileItemView;
        }



        @Override
        public void run() {
            super.run();
            try {
                URL url = new URL(urlStr);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                Logger.e("----apkUrl----" + length);
                InputStream is = conn.getInputStream();

                String saveFileName=dirPath+File.separator+MD5Util.string2MD5(model.getUrl())+"_temp";
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);
                int count = 0;
                byte buf[] = new byte[1024];
                while (true) {
                    int numread = is.read(buf);

                    count += numread;
                    progress = (int) (((float) count / length) * 100);

                    // 更新进度
                    Message msg = handler.obtainMessage();
                    msg.what = 1;
                    msg.arg1 = progress;
                    if (progress >= lastRate + 1) {
                        if (progress % 2 == 1) {
                            handler.sendMessage(msg);
                            lastRate = progress;
                        }
                    }
                    if (numread <= 0) {
                        // 下载完成通知安装
                        handler.sendEmptyMessage(0);
                        // 下载完了，cancelled也要设置
                        Logger.e("下载完毕");
                        break;
                    }
                    fos.write(buf, 0, numread);
                }
                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                Logger.e(e.getLocalizedMessage(), e);

            }

        }
    }


    class ProgressHandler extends  Handler{

        RoundProgressBar view;
        FileModel model;
        View fileItemView;

        public ProgressHandler(RoundProgressBar view, FileModel model,View fileItemView) {
            this.view = view;
            this.model = model;
            this.fileItemView = fileItemView;
        }

        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);

            switch (msg.what) {
                case 0:
                    // 下载完毕
                    // 取消通知
                    Logger.e("下载完毕");
                    view.setVisibility(View.GONE);
                    fileItemView.setVisibility(View.VISIBLE);
                    String saveFileName=dirPath+File.separator+MD5Util.string2MD5(model.getUrl())+"_temp";
                    String prefix=model.getUrl().substring(model.getUrl().lastIndexOf(".")+1);

//                    File newfile=new File(dirPath+File.separator+MD5Util.string2MD5(model.getUrl())+"."+prefix);
                    File newfile=new File(dirPath+File.separator+model.getName());
                    new File(saveFileName).renameTo(newfile);
                    notifyDataSetChanged();
                    break;
                case 1:
                    int rate = msg.arg1;
                    if (rate < 100) {
                        Logger.e("rate-" + rate);
                    }
                    view.setVisibility(View.GONE);
                    fileItemView.setVisibility(View.VISIBLE);
                    String saveFileName1=dirPath+File.separator+MD5Util.string2MD5(model.getUrl())+"_temp";
                    String prefix1=model.getUrl().substring(model.getUrl().lastIndexOf(".")+1);
                    File newfile1=new File(dirPath+File.separator+model.getName());
                    new File(saveFileName1).renameTo(newfile1);
                    notifyDataSetChanged();
                    break;
            }

        }
    }

}
